package com.example.starter.redis.configure;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author 王令
 * @since 2022-05-06 22:25:56
 */
public class RedisAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean({RedisTemplate.class})
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);

        // 设置键序列化器
        template.setKeySerializer(new StringRedisSerializer());
        // 设置 Hash 键序列化器
        template.setHashKeySerializer(template.getKeySerializer());
        // 设置值序列化器
        template.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
        // 设置 Hash 值序列化器
        template.setHashValueSerializer(template.getValueSerializer());

        template.afterPropertiesSet();
        return template;
    }

}
